﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace Coway.Ordering.Orders
{
    /// <summary>
    /// 参考EasyAbp的EShop项目
    /// </summary>
    public class NewOrderGenerator : INewOrderGenerator, ITransientDependency
    {
        public async Task<Order> GenerateAsync(CreateUpdateOrderDto input)
        {
            var orderItems = new List<OrderItem>();

            var order = new Order(
                input.OrderNo,
                input.ReferralNo,
                input.BuyWay
                );

            // 重新生成一个订单号
            order.OrderNo = DateTime.Now.ToString("yyyyMMdd") + Guid.NewGuid().ToString();
            order.Remarks = input.Remarks;
            order.SellerCode = input.SellerCode;
            order.SellerName = input.SellerName;
            order.SellerPhone = input.SellerPhone;

            if (input.OrderItems?.Any() == true)
            {
                for (var i = 0; i < input.OrderItems.Count; i++)
                {
                    var inputOrderItem = input.OrderItems[i];
                    inputOrderItem.No = inputOrderItem.No <= 0 ? i + 1 : inputOrderItem.No;
                    orderItems.Add(await GenerateOrderLineAsync(input, order, inputOrderItem));
                }
                //foreach (var inputOrderItem in input.OrderItems)
                //{
                //    orderItems.Add(await GenerateOrderLineAsync(input, order, inputOrderItem));
                //}
            }

            //var storeCurrency = await GetStoreCurrencyAsync(input.StoreId);

            //if (orderLines.Any(x => x.Currency != storeCurrency))
            //{
            //    throw new CurrencyIsLimitException(storeCurrency);
            //}

            //var productTotalPrice = orderLines.Select(x => x.TotalPrice).Sum();

            //// Todo: totalPrice may contain other fee.
            //var totalPrice = productTotalPrice;
            //var totalDiscount = orderLines.Select(x => x.TotalDiscount).Sum();



            //input.MapExtraPropertiesTo(order, MappingPropertyDefinitionChecks.Destination);

            order.SetOrderItems(orderItems);

            //order.SetOrderNumber(await _orderNumberGenerator.CreateAsync(order));

            return order;
        }

        protected virtual async Task<OrderItem> GenerateOrderLineAsync(CreateUpdateOrderDto input,
            Order order,
            CreateOrderItemDto inputOrderLine)
        {
            //var product = productDict[inputOrderLine.ProductId];
            //var productSku = product.GetSkuById(inputOrderLine.ProductSkuId);

            //if (!inputOrderLine.Quantity.IsBetween(productSku.OrderMinQuantity, productSku.OrderMaxQuantity))
            //{
            //    throw new OrderLineInvalidQuantityException(product.Id, productSku.Id, inputOrderLine.Quantity);
            //}

            //var totalPrice = productSku.Price * inputOrderLine.Quantity;

            var orderItem = new OrderItem(Guid.NewGuid(), order.Id)
            {
                Model = inputOrderLine.Model,
                OrderTax = inputOrderLine.OrderTax,
                ContractDuration = inputOrderLine.ContractDuration,
                GrandTotal = inputOrderLine.GrandTotal,
                MonthlyRent = inputOrderLine.MonthlyRent,
                Total = inputOrderLine.Total,
                SalesPrice = inputOrderLine.SalesPrice,
                RegistrationFee = inputOrderLine.RegistrationFee,
                Quantity = inputOrderLine.Quantity,
                No = inputOrderLine.No,
                MonthlyPaymentMethod = inputOrderLine.MonthlyPaymentMethod,
            };

            //inputOrderLine.MapExtraPropertiesTo(orderLine, MappingPropertyDefinitionChecks.Destination);

            return orderItem;
        }
    }
}
